package com.sf.fy.uav.applet.order.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.sf.fy.uav.common.enums.*;
import com.sf.fy.uav.common.request.order.BillAddRequest;
import com.sf.fy.uav.common.response.order.BillingResponse;
import com.sf.fy.uav.common.utils.DateUtils;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.order.controller.BillRest;
import com.sf.fy.uav.order.controller.OrderInfoRest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @author LTQ
 */
@RestController
@RequestMapping("/home/billing/management/")
@Api(tags = "账单管理")
public class SysBillingManagementController {
    private final static Logger logger = LoggerFactory.getLogger(SysBillingManagementController.class);

    @Autowired
    private OrderInfoRest orderInfoRest;

    @Autowired
    private BillRest billRest;

    /**
     * 日期格式 年 月 日 如2009-02-26
     */
    public static final String DATEFORMATDAY = "yyyy-MM-dd";

    private static final Integer CONST_NUM = 0;


    @GetMapping("get-billings")
    @CrossOrigin
    public Rs<List<BillingResponse>> getBillings(@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) String tcWaybillNo, @RequestParam(required = false) String tradeNo, @RequestParam(required = false) Integer type, @RequestParam(required = false) Integer platformCode, @RequestParam(required = false) String enterpriseId, @RequestParam(required = false) Integer payStatus
            , @RequestParam(required = false) String startTransactionTime, @RequestParam(required = false) String endTransactionTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMATDAY);
        Date startTransactionTimeDate = null;
        Date endTransactionTimeDate = null;
        try {
            if (StringUtils.isNotBlank(startTransactionTime)) {
                startTransactionTimeDate = DateUtils.getDayFirstTime(dateFormat.parse(startTransactionTime));
            }
            if (StringUtils.isNotBlank(endTransactionTime)) {
                endTransactionTimeDate = DateUtils.getDayLastTime(dateFormat.parse(endTransactionTime));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Rs.success(orderInfoRest.getBillings(page, size, tcWaybillNo, tradeNo, type, platformCode, enterpriseId, payStatus, startTransactionTimeDate, endTransactionTimeDate));
    }

    @GetMapping("get-total")
    @CrossOrigin
    public Rs<Long> getTotal(@RequestParam(required = false) String tcWaybillNo, @RequestParam(required = false) String tradeNo, @RequestParam(required = false) Integer type, @RequestParam(required = false) Integer platformCode, @RequestParam(required = false) String enterpriseId, @RequestParam(required = false) Integer payStatus
            , @RequestParam(required = false) String startTransactionTime, @RequestParam(required = false) String endTransactionTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMATDAY);
        Date startTransactionTimeDate = null;
        Date endTransactionTimeDate = null;
        try {
            if (StringUtils.isNotBlank(startTransactionTime)) {
                startTransactionTimeDate = DateUtils.getDayFirstTime(dateFormat.parse(startTransactionTime));
            }
            if (StringUtils.isNotBlank(endTransactionTime)) {
                endTransactionTimeDate = DateUtils.getDayLastTime(dateFormat.parse(endTransactionTime));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Rs.success(orderInfoRest.getTotal(tcWaybillNo, tradeNo, type, platformCode, enterpriseId, payStatus, startTransactionTimeDate, endTransactionTimeDate));
    }


    @GetMapping("export")
    @ApiOperation(value = "导出", notes = "/export")
    public void export(HttpServletResponse response, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) String tcWaybillNo, @RequestParam(required = false) String tradeNo, @RequestParam(required = false) Integer type, @RequestParam(required = false) Integer platformCode, @RequestParam(required = false) String enterpriseId, @RequestParam(required = false) Integer payStatus, @RequestParam(required = false) String startTransactionTime, @RequestParam(required = false) String endTransactionTime, @RequestParam(required = false) Integer platform) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            String fileName = "账单明细表" + sdf.format(new Date());
            response.setHeader("content-disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8) + ".xls");
            ExportParams exportParams = new ExportParams();
            Rs<List<BillingResponse>> listRs = this.getBillings(page, size, tcWaybillNo, tradeNo, type, platformCode, enterpriseId, payStatus, startTransactionTime, endTransactionTime);
            List<BillingResponse> billingResponses = listRs.getData();
            for (BillingResponse billingResponse : billingResponses) {
                billingResponse.setPlatformCodeString(PlatformCodeEnum.getName(billingResponse.getPlatformCode()));
                if (ObjectUtils.allNotNull(platform) && PlatformCodeEnum.FY_SCENIC_SPOT.getCode().equals(platform)) {
                    billingResponse.setPlatformCodeString(PlatformCodeEnum.FY_SCENIC_SPOT.getName());
                }
                billingResponse.setTypeString(OrderTypeEnum.getDesc(billingResponse.getType()));
                billingResponse.setCurrency("CNY");
                billingResponse.setPayStatusString(PayStatusEnum.getValue(billingResponse.getPayStatus()));
                billingResponse.setSettleChannel(SettleChannelEnum.getName(billingResponse.getSettleChannel()));
                billingResponse.setPayChannel(PayChannelEnum.getName(billingResponse.getPayChannel()));
                if (ObjectUtils.allNotNull(billingResponse.getPricePaid()) && billingResponse.getPricePaid().compareTo(BigDecimal.ZERO) > CONST_NUM) {
                    billingResponse.setPricePaid(billingResponse.getPricePaid().setScale(2, RoundingMode.HALF_UP));
                }
            }
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, BillingResponse.class, billingResponses);
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @PostMapping("bill-settlement")
    public Rs<Boolean> billSettlement(@RequestBody BillAddRequest billAddRequest) {
        return billRest.billSettlement(billAddRequest);
    }
}
